package com.jiuyin.dianjing.ui.fragment.search;

import android.content.Intent;
import android.widget.ImageView;

import androidx.recyclerview.widget.DefaultItemAnimator;

import com.bumptech.glide.Glide;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.adapter.BaseRecyclerAdapter;
import com.jiuyin.dianjing.adapter.SmartViewHolder;
import com.jiuyin.dianjing.api.base.DefaultApiResult;
import com.jiuyin.dianjing.api.enums.ApiEnum;
import com.jiuyin.dianjing.api.interfaces.ApiResultCallback;
import com.jiuyin.dianjing.api.server.ServerApi;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.enums.SearchFragment;
import com.jiuyin.dianjing.event.MatchInfoResultMsgEvent;
import com.jiuyin.dianjing.event.MsgDispatcher;
import com.jiuyin.dianjing.event.WordMsgEvent;
import com.jiuyin.dianjing.model.Compete;
import com.jiuyin.dianjing.ui.activity.matchInfo.MatchInfoDetailActivity;
import com.jiuyin.dianjing.ui.fragment.base.BaseRefreshFragment;
import com.jiuyin.dianjing.util.DisplayUtil;
import com.jiuyin.dianjing.util.IMEUtil;
import com.jiuyin.dianjing.util.LogUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_ANTISTOP_LIST;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_COMPETENAME;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_COMPET_ID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_COURSE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_IS_CREATOR;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_LOGO;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_NAME;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_NUM;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TIME;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TYPE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_WORD;
import static com.jiuyin.dianjing.api.constant.ApiConstant.PAGE_FIRST;
import static com.jiuyin.dianjing.api.constant.ApiConstant.PAGE_NUM;

/*
 *
 * 赛事资讯搜索结果列表界面
 */
public class SearchMatchInfoResultFragment extends BaseRefreshFragment<Compete> {
    private MatchInfoResultMsgEvent mMatchInfo;

    public SearchMatchInfoResultFragment() {
        super(PAGE_NUM);
        EventBus.getDefault().register(this);
    }

    /**
     * 通过关键字像服务器请求搜索内容
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void searchRequest(MatchInfoResultMsgEvent event) {
        mPageNum = PAGE_FIRST;
        mMatchInfo = event;
        doSearchRequest();
    }

    @Override
    public void fetchData() {
        doSearchRequest();
    }

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_search_result;
    }

    @Override
    protected void initData() {
        mAdapter = new BaseRecyclerAdapter<Compete>(R.layout.item_info_match) {
            @Override
            protected void onBindViewHolder(SmartViewHolder holder, Compete model, int position) {
                if (null != model) {
                    holder.text(R.id.tv_match_title, model.competename);
                    holder.text(R.id.tv_match_name, model.name);
                    holder.text(R.id.tv_match_time, model.time);
                    holder.text(R.id.tv_match_status, model.course);
                    ImageView ivGame = holder.itemView.findViewById(R.id.img_match);
                    Glide.with(getContext())
                            .load(model.logo)
                            .override(DisplayUtil.dp2px(getContext(), 100), DisplayUtil.dp2px(getContext(), 70.7f))
                            .into(ivGame);
                }
            }
        };
        mAdapter.setOnItemClickListener((parent, view, position, id) -> {
            Compete model = mAdapter.getItem(position);
            Intent intent = new Intent(getActivity(), MatchInfoDetailActivity.class);
            intent.putExtra(KEY_COMPET_ID, model.compet_id);
            intent.putExtra(KEY_NAME, model.name);
            intent.putExtra(KEY_IS_CREATOR, model.isCreator);
            startActivity(intent);
        });
        mRcvPage.setItemAnimator(new DefaultItemAnimator());
        mRcvPage.setAdapter(mAdapter);
    }

    @Override
    protected void initView() {
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 向服务器请求关键搜索内容
     */
    private void doSearchRequest() {
        if (null != mMatchInfo) {
            String msg = mMatchInfo.getMsg();
            String type = mMatchInfo.getType();
            LogUtil.log("SearchMatchInfoResultFragment doSearchRequest msg = " + msg + ",type = " + type);
            MsgDispatcher msgDispatcher = new MsgDispatcher(SearchFragment.SUGGEST);
            msgDispatcher.setWordMsgEvent(new WordMsgEvent(msg));
            EventBus.getDefault().post(msgDispatcher);
            HashMap<String, Object> params = new HashMap<>();
            params.put(KEY_WORD, msg);
            params.put(KEY_NUM, mPageNum);
            params.put(KEY_TOKEN, HelperApplication.getToken());
            params.put(KEY_TYPE, type);
            JSONObject jsonObject = new JSONObject(params);
            ApiResultCallback requestCallback = new DefaultApiResult() {
                @Override
                public void onSuccess(JsonObject data) {
                    IMEUtil.hideInputMethod(getActivity());
                    if (null != data && data.has(KEY_ANTISTOP_LIST)) {
                        LogUtil.log("SearchMatchInfoResultFragment appGetHomeSearchByWord onSuccess = " + data.toString());
                        JsonArray jsonArray = data.getAsJsonArray(KEY_ANTISTOP_LIST);
                        if (jsonArray != null) {
                            int size = jsonArray.size();
                            if (0 != size) {
                                List<Compete> competeList = new ArrayList<>();
                                for (int i = 0; i < size; i++) {
                                    JsonObject object = jsonArray.get(i).getAsJsonObject();
                                    Compete model = new Compete();
                                    String competename = object.get(KEY_COMPETENAME).getAsString();
                                    String compet_id = object.get(KEY_COMPET_ID).getAsString();
                                    String name = object.get(KEY_NAME).getAsString();
                                    String logo = object.get(KEY_LOGO).getAsString();
                                    String course = object.get(KEY_COURSE).getAsString();
                                    String time = object.get(KEY_TIME).getAsString();
                                    model.compet_id = compet_id;
                                    model.competename = competename;
                                    model.name = name;
                                    model.course = course;
                                    model.logo = logo;
                                    model.time = time;
                                    competeList.add(model);
                                }
                                dealWithSuccessInfo(competeList);
                            } else {
                                dealOtherInfo();
                            }
                        }
                    }
                }

                @Override
                public void onFail(String msg) {
                    super.onFail(msg);
                    dealOtherInfo();
                }

                @Override
                public void onError(String msg) {
                    super.onError(msg);
                    dealOtherInfo();
                }
            };
            ServerApi.post(ApiEnum.APP_GET_SEARCH_BYWORD_API.getUrl(), jsonObject, null, progress, null, requestCallback);
        }
    }
}